package com.dzirtbry.ticatac.game;

import java.awt.Point;
import java.util.ArrayList;

import com.dzirtbry.ticatac.ai.AI;
import com.dzirtbry.ticatac.pane.TicTacMarker;
import com.dzirtbry.ticatac.pane.TicTacPane;

public class GameModel {
	public static final int HUMAN = 1;
	public static final int PC = 2;
	private int[] user;
	private TicTacPane pane;
	private int currentTurn;
	private int turn;
	private static int game;
	private boolean finished;

	private ArrayList<GameModelListner> listners;
	
	static {
		game = 0;
	}
	
	public GameModel() {
		this(GameSettings.getInstance().getUser1(), GameSettings.getInstance().getUser2());
	}
	
	public GameModel(int user1, int user2) {
		game++;
		turn = 0;
		System.out.println("Game #" + game);
		listners = new ArrayList<GameModelListner>();
		finished = false;
		user = new int[3];
		user[1] = user1;
		user[2] = user2;
		pane = new TicTacPane();
		currentTurn = TicTacMarker.TAC;
		checkState();
	}
	
	public void addListner(GameModelListner listner) {
		listners.add(listner);
	}
	
	public void removeListner(GameModelListner listner) {
		listners.remove(listner);
		System.out.println(listners);
	}

	
	public boolean isFinished() {
		return finished;
	}

	public void setFinished(boolean finished) {
		this.finished = finished;
	}

	
	public TicTacPane getPane() {
		return pane; 
	}
	
	public int getUser1(){
		return user[1];
	}
	
	public int getUser2(){
		return user[2];
	}
	
	private boolean isMoveAvaliable (Point point) {
		return !finished && pane.isMoveAvaliable(point);
	}
	
	public void move(Point point) {
		if (!isMoveAvaliable(point))
			return;
		turn++;
		pane.setMarker(point, currentTurn);
		System.out.println("Current turn: " + turn);
		pane.print();
		firePaneChaned();
		checkState();
	}
	
	private void checkState() {
		if (pane.getVictorious() != TicTacMarker.NO) {
			fireVictory(pane.getVictorious());
			return;
		}
		if (!pane.isMoveAvaliable()) {
			fireGameOver();
			return;
		}
		changeTurn();
	}
	
	private void changeTurn() {
		currentTurn = currentTurn==TicTacMarker.TIC ? TicTacMarker.TAC : TicTacMarker.TIC;
		if (user[currentTurn] == GameModel.PC) {
			move(AI.makeMove(pane, currentTurn));
		}
	}
	
	private void firePaneChaned () {
		for (GameModelListner listner: listners) {
			listner.paneChanged();
		}
	}
	
	private void fireVictory(int user) {
		finished = true;
		System.out.println("User " + user + " won!");
		for (GameModelListner listner: listners) {
			listner.gameOver(user);
		}
	}
	
	private void fireGameOver() {
		finished = true;
		System.out.println("Game over. Nobody won.");
		for (GameModelListner listner: listners) {
			listner.gameOver(TicTacMarker.NO);
		}
	}
	

}
